package edu.ynu.se.xiecheng.achitectureclass.service.Impl;

import edu.ynu.se.xiecheng.achitectureclass.dao.CameraDataDao;
import edu.ynu.se.xiecheng.achitectureclass.dao.DeviceDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.CameraDataEntity;
import edu.ynu.se.xiecheng.achitectureclass.entity.DeviceEntity;
import edu.ynu.se.xiecheng.achitectureclass.service.CameraDataService;
import edu.ynu.se.xiecheng.achitectureclass.service.CameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CameraDataServiceImpl implements CameraDataService {

    @Autowired
    private CameraService cameraService;  // 调用摄像头接口服务

    @Autowired
    private CameraDataDao cameraDataDao;

    @Autowired
    private DeviceDao deviceDao;

    @Override
    public String captureAndSaveImage() {
        Long deviceId = 6L;

        // 获取图片URL
        String picUrl = cameraService.captureImage();

        if (picUrl != null) {
            // 创建 CameraDataEntity 实体对象
            CameraDataEntity cameraDataEntity = new CameraDataEntity();
            cameraDataEntity.setPhoto(picUrl);  // 存储图片URL

            // 获取 DeviceEntity 实例（假设通过 deviceId 获取）
            DeviceEntity device = deviceDao.findById(deviceId)
                    .orElseThrow(() -> new IllegalArgumentException("Device not found"));

            // 设置外键关系，关联设备实体
            cameraDataEntity.setDevice(device);

            // 将 CameraDataEntity 保存到数据库
            cameraDataDao.save(cameraDataEntity);

            return picUrl;
        } else {
            throw new RuntimeException("获取图片失败，无法保存");
        }
    }

    @Override
    public List<String> getLastThreePhotos() {
        // 创建分页对象：第一页，3条记录，按ID降序
        Pageable pageable = PageRequest.of(0, 3);
        Page<String> page = cameraDataDao.findLastThreePhotos(pageable);
        return page.getContent();  // 获取查询结果，返回照片路径列表
    }

}
